package com.wxw.getapp

import android.Manifest
import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import com.wxw.getapp.adapter.AppAdapter
import kotlinx.android.synthetic.main.activity_main.*
import android.content.pm.PackageManager
import android.os.*
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Toast
import com.safframework.log.L
import com.wxw.getapp.activity.SetActivity
import com.wxw.getapp.bean.AppInfo
import com.wxw.getapp.utils.AppUtils
import android.os.StrictMode
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.inputmethod.InputMethodManager




class MainActivity : AppCompatActivity(),View.OnClickListener {


    lateinit var adapter: AppAdapter
    var applistData = ArrayList<AppInfo>()
    var appSearchList = ArrayList<AppInfo>()
    lateinit  var content:Context
    var flag = true
    var i = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initPhotoError()
        requestPermission()
        initview()
        adapter = AppAdapter(this)
        applv.setOnTouchListener { v, event ->
            when(event.action){
                MotionEvent.ACTION_DOWN,MotionEvent.ACTION_UP,MotionEvent.ACTION_MOVE->{
                    InputMethodHint()
                }
            }
            super.onTouchEvent(event)
        }

        applv.adapter = adapter
        avi.visibility = View.VISIBLE
        avi.show()
        Thread(CopyRunnable()).start()
//        mHandler.sendEmptyMessage(111)


    }

    fun InputMethodHint(){
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val isOpen = imm.isActive
        if (isOpen){
            val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager!!.hideSoftInputFromWindow(this@MainActivity.getCurrentFocus().getWindowToken()
                    , InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    private var exitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(applicationContext, "再按一次退出程序", Toast.LENGTH_SHORT).show()
                exitTime = System.currentTimeMillis()
            } else {
                finish()
                System.exit(0)
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }


    private fun initview() {
        content = this
        search_button.setOnClickListener(this)
        search_back.setOnClickListener(this)
        setting_iv.setOnClickListener(this)
        search_edit.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                for (app in applistData){
                    var edit_str = search_edit.text.toString().trim()

                    if (edit_str.length==0){
                        adapter.setBeanData(applistData)
                        adapter.notifyDataSetChanged()
                        return
                    }else if (app.appName.contains(edit_str)
                            ||app.packageName.contains(edit_str)){
                        appSearchList.add(app)
                        i++
                    }
                }
                if (appSearchList.size != 0){
                    var appSearchList_copy = appSearchList
                    adapter.setBeanData(appSearchList_copy)
                    adapter.notifyDataSetChanged()
                    appSearchList  = ArrayList<AppInfo>()
                }
            }

        })
    }

    override fun onClick(v: View?) {
        when(v){
            search_button->{
                search_rl.visibility = View.VISIBLE
                rl_title.visibility = View.GONE
                search_edit.setFocusable(true);
                search_edit.setFocusableInTouchMode(true);
                search_edit.requestFocus();
            }
            search_back->{
                search_edit.setText("")
                search_rl.visibility = View.GONE
                rl_title.visibility = View.VISIBLE
                InputMethodHint()

            }
            setting_iv->{
                var intent = Intent(this@MainActivity,SetActivity::class.java)
                startActivity(intent)
            }
        }
    }

    private inner class CopyRunnable : Runnable {
        override fun run() {
//            Thread.sleep(5000)
            applistData = AppUtils.getAppInfos(content) as ArrayList<AppInfo>
            L.d(applistData[0].appName+applistData[0].packageName+applistData[0].drawable)
//                    for (data in applistData){
//                        L.d(data.appName+data.packageName+data.drawable)
//                    }

            this@MainActivity.runOnUiThread {
                app_num.text = "App列表（"+applistData.size+")"
                adapter.setBeanData(applistData)
                adapter.notifyDataSetChanged()
                avi.hide()
            }
        }

    }

    private fun initPhotoError() {
        // android 7.0系统解决拍照的问题
        val builder = StrictMode.VmPolicy.Builder()
        StrictMode.setVmPolicy(builder.build())
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            builder.detectFileUriExposure()
        }
    }
    private inner class getuserPermission :Runnable{
        override fun run() {
            Thread.sleep(2000)
            if (flag){
                requestPermission()
                flag = false
            }
        }

    }

    // 创建一个Handler
    private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg?.what) {
                111 ->{


                }

            }
        }
    }

    private fun initdata(){
//        for ( num in 1..15){
//            items.add(num.toString())
//        }

//        items = AppUtils.getBitmap(this) as ArrayList<String>
     }

    /**
     * 动态申请权限
     */
    fun requestPermission() {
        val checkSelfPermission = ContextCompat.checkSelfPermission(this@MainActivity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
        if (checkSelfPermission == PackageManager.PERMISSION_GRANTED) {
            //todo :has ready get permission write your code here
        } else {
            //requset permission
        }
        ActivityCompat.requestPermissions(this@MainActivity,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 5)
    }

    //然后再onRequestPermissionsResult中进行判断操作：
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,grantResults: IntArray) {
        //super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 5) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && permissions[0] == Manifest.permission.WRITE_EXTERNAL_STORAGE) {
                //todo:permission granted
//                Toast.makeText(this@MainActivity,"permission       granted",Toast.LENGTH_SHORT).show()
            } else{
                //todo:permission denied
                Toast.makeText(this@MainActivity,"请允许储存权限，以保证app正常运行",Toast.LENGTH_LONG).show()

               Thread(getuserPermission()).start()

            }
        }
    }








}
